package xyz.zhzby.cyzx.ucenter.util;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import xyz.zhzby.cyzx.security.entity.User;

import java.util.concurrent.TimeUnit;

/**
 * @author zby
 * @date 2021/12/16
 */
@Component
public class RedisUtil implements InitializingBean {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    static RedisTemplate<String, Object> REDIS_TEMPLATE;

    @Override
    public void afterPropertiesSet() throws Exception {
        REDIS_TEMPLATE = redisTemplate;
    }

    @ApiOperation("修改用户信息，且不修改其过期时间")
    public static void updateUserInfo(User user) {
        String key = "loginUser:info:" + user.getUsername();
        Long expire = REDIS_TEMPLATE.opsForValue().getOperations().getExpire(key);
        if (expire == null) {
            expire = 60 * 60 * 2L;
        }
        REDIS_TEMPLATE.opsForValue().set(key, user, expire, TimeUnit.SECONDS);
    }

    @ApiOperation("根据key将验证码放入redis")
    public static void setVerificationCode(String key, String code) {
        REDIS_TEMPLATE.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
    }

    @ApiOperation("根据key获取验证码")
    public static String getVerificationCode(String key) {
        return (String) REDIS_TEMPLATE.opsForValue().get(key);
    }
}
